package com.jiangnan.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat.startActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.google.zxing.BarcodeFormat
import com.google.zxing.integration.android.IntentIntegrator
import com.jiangnan.databinding.FragmentRespositoryBinding
import com.jiangnan.entity.Book
import com.jiangnan.ui.activity.AdminBookActivity
import com.jiangnan.ui.activity.BookMainActivity
import com.jiangnan.ui.activity.ItemAdapterRepositoryActivity
import com.jiangnan.ui.adapter.RepositoryQuickAdapter
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.NavigationUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.BookViewModel
import com.jiangnan.viewmodel.ISBNViewModel
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [RespositoryFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class RespositoryFragment : Fragment(), View.OnClickListener,
    BaseQuickAdapter.OnItemClickListener<Book> {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    private lateinit var binding: FragmentRespositoryBinding
    private lateinit var bookviewModel: BookViewModel
    private var page: Int? = 1
    private var pageSize: Int? = 15
    private var requestParam: String? = ""
    private var currentUserId: Long? = null
    private var role: Int? = null
    private var TAG = "RespositoryFragment"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate<FragmentRespositoryBinding>(
            inflater,
            com.jiangnan.R.layout.fragment_respository,
            container,
            false
        )
        bookviewModel = ViewModelProvider(this)[BookViewModel::class.java]
        searchFragmentSelector()
        toastMessage()

        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val recyclerView = binding.recyclerViewRepository
        recyclerView.layoutManager =
            StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        val adapter = RepositoryQuickAdapter()
        recyclerView.adapter = adapter

        observe(adapter)

        initRefreshLayout()

        adapter.setOnItemClickListener(this)

        initItem(page, pageSize, requestParam)
        // 设置点击监听器为 Fragment 本身
        binding.overlayButton.setOnClickListener(this)
        binding.repositoryTvButtonSearch.setOnClickListener(this)
        binding.ivClear.setOnClickListener(this)

    }


    /**
     * 观察数据都放在这里
     */
    private fun observe(adapter: RepositoryQuickAdapter) {
        // 观察数据仅设置一次
        bookviewModel.bookList.observe(viewLifecycleOwner) { bookList ->
            adapter.submitList(bookList)
        }
        bookviewModel.total.observe(viewLifecycleOwner) { total ->
            if (requestParam == "") {
                binding.tvTotal.text = "本馆图书共有 " + total + " 本"
            } else {
                binding.tvTotal.text = "符合条件的图书共有 " + total + " 本"
            }

        }

        /**
         * 监听当前登录用户信息，并根据不同角色显示不同按钮
         */
        if (SharedPrefUtil.getLoginInfo(requireContext()) != null) {
            currentUserId = SharedPrefUtil.getLoginInfo(requireContext())!!.id.toLong()
            role = SharedPrefUtil.getLoginInfo(requireContext())!!.role
            binding.overlayButton.setText(
                when (role) {
                    0 -> "新书\n入库"
                    else -> "扫码\n借书"
                }
            )
            Log.d(TAG, "当前登录用户角色为：" + role)
        }


//        CurrentLoginInfo.currentLoginInfo.observe(viewLifecycleOwner) {
//            currentUserId = it.id.toLong()
//            role = it.role
////            binding.overlayButton.visibility=when(role){
////                0 -> View.VISIBLE
////                else -> View.GONE
////            }
//            binding.overlayButton.setText(
//                when (role) {
//                    0 -> "新书\n入库"
//                    else -> "扫码\n借书"
//                }
//            )
//            Log.d(TAG, "当前登录用户角色为：" + it.role)
//        }
    }

    /**
     * 初始化列表
     */
    private fun initItem(page: Int?, pageNum: Int?, requestParam: String?) {
        bookviewModel.getAllBooks(page, pageNum, requestParam)
//        ToastUtil.showLong(requireContext(), "加载中..."+ viewModel._total.value)
    }

    /**
     * 初始化刷新布局，并设置监听器
     */
    private fun initRefreshLayout() {
        val refreshLayout = binding.refreshLayoutRepository as RefreshLayout
        refreshLayout.setRefreshHeader(ClassicsHeader(context))
        refreshLayout.setRefreshFooter(ClassicsFooter(context))
        refreshLayout.setOnRefreshListener { refreshlayout ->
            page = 1
            initItem(page, pageSize, requestParam)
            refreshlayout.finishRefresh(true)
        }

        refreshLayout.setOnLoadMoreListener { refreshlayout ->
            if (page!! * pageSize!! < bookviewModel.total.value!!) {
                page = page!!.plus(1)
                initItem(page, pageSize, requestParam)
                refreshlayout.finishLoadMore(true)
            } else {
                ToastUtil.showLong(requireContext(), "没有更多数据了")
                refreshlayout.finishLoadMore(false)
            }
        }

    }

    /**
     * 给自定义搜索框设置样式
     */
    private fun searchFragmentSelector() {
        // 设置焦点变化监听器来恢复父容器的原始状态
        binding.repositoryEtSearch.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
                    // 当输入框失去焦点时，恢复父容器的原始背景
                    binding.repositoryFlSearchLayout.setBackgroundResource(com.jiangnan.R.drawable.edittext_default_bg)
                } else {
                    // 可选：如果需要，在获得焦点时也改变背景
                    binding.repositoryFlSearchLayout.setBackgroundResource(com.jiangnan.R.drawable.edittext_pressed_bg)
                }
            }
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment RespositoryFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            RespositoryFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }

    private fun toastMessage() {
        bookviewModel.toastMessage.observe(viewLifecycleOwner) { event ->
            event.getContentIfNotHandled()?.let { message ->
                ToastUtil.showShort(requireContext(), message)
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            binding.overlayButton.id -> {
                if (role == 0) {
                    NavigationUtil.navigateTo(requireContext(), BookMainActivity::class.java)
                } else {
                    borrowBookByIsbn()
                    // 测试用的isbn
//                    bookviewModel.borrowBookByQrcode(currentUserId!!, "9787559855022")
                }
            }

            binding.repositoryTvButtonSearch.id -> {
                requestParam = binding.repositoryEtSearch.text.toString()
                page = 1
                bookviewModel.getAllBooks(page, pageSize, requestParam)
                ToastUtil.showShort(requireContext(), "点击了搜索按钮")
            }

            binding.ivClear.id -> {
                binding.repositoryEtSearch.text.clear()
                requestParam = ""
                page = 1
                bookviewModel.getAllBooks(page, pageSize, requestParam)
            }
        }
//        initItem()
    }

    private fun borrowBookByIsbn() {
        val integrator = IntentIntegrator.forSupportFragment(this)
        integrator.setDesiredBarcodeFormats(
            listOf(
                BarcodeFormat.EAN_13.name, // 常见的图书ISBN格式
                BarcodeFormat.UPC_A.name,  // 其他一维码格式
                BarcodeFormat.QR_CODE.name // 二维码格式
            )
        )
        integrator.setPrompt("请扫描图书ISBN")
        integrator.setCameraId(0) // 使用后置摄像头
        integrator.setBeepEnabled(true)
        integrator.setBarcodeImageEnabled(false)
        integrator.initiateScan()
    }

    // 处理扫描结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                // 取消扫描
                ToastUtil.showShort(requireContext(), "扫描取消")
            } else {
                // 成功扫描到结果（ISBN）
                bookviewModel.borrowBookByQrcode(currentUserId!!, result.contents)
                ToastUtil.showShort(
                    requireContext(),
                    "扫描成功,扫描到的ISBN码为：${result.contents}"
                )
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }


    override fun onClick(adapter: BaseQuickAdapter<Book, *>, view: View, position: Int) {
        val book = adapter.getItem(position)
        if (role == 0) {
            var intent = Intent(requireContext(), AdminBookActivity::class.java)
            if (book != null) {
                intent.putExtra("book", book)  // 传递 Book 对象
            }
            startActivity(intent)
        } else {
            val intent = Intent(requireContext(), ItemAdapterRepositoryActivity::class.java)
            intent.putExtra("book", book)  // 传递 Book 对象
            startActivity(intent)
        }

    }
}




